package com.leyou.item.web;

import com.leyou.item.dto.CategoryDTO;
import com.leyou.item.entity.Category;
import com.leyou.item.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/category")
public class CategoryController {

    @Autowired
    private CategoryService categoryService;

    //根据分类id，查询商品分类
    @GetMapping("/{id}")
    public ResponseEntity<CategoryDTO> queryCategoryById(@PathVariable("id") Long id){
        // 根据id查询
        Category category = categoryService.getById(id);
        // PO转DTO
        CategoryDTO categoryDTO = new CategoryDTO(category);
        // 封装结果，返回200
        //return ResponseEntity.status(HttpStatus.OK).body(categoryDTO);
        return ResponseEntity.ok(categoryDTO);
    }

    //根据分类id的集合，查询商品分类的集合
    //http://localhost:8081/category/list?ids=1,2,3
    //http://localhost:8081/category/list?ids=1&ids=2&ids=3
    @GetMapping("/list")
    public ResponseEntity<List<CategoryDTO>> queryCategoryByIds(@RequestParam("ids") List<Long> ids){
        // 根据id批量查询
        List<Category> categoryList = categoryService.listByIds(ids);
        // 转换DTO集合

        //方式一
//        List<CategoryDTO> categoryDTOList = new ArrayList<>(categoryList.size());
//        for (Category category : categoryList) {
//            CategoryDTO categoryDTO = new CategoryDTO(category);
//            categoryDTOList.add(categoryDTO);
//        }

        //方式二  流
//        List<CategoryDTO> categoryDTOList = categoryList.stream()
//                //.map(category -> new CategoryDTO(category))
//                .map(CategoryDTO::new)
//                .collect(Collectors.toList());

        //方式三
        List<CategoryDTO> categoryDTOList = CategoryDTO.convertEntityList(categoryList);
        // 返回200
        return ResponseEntity.ok(categoryDTOList);
    }

    //根据父类目id，查询子类目的集合
    @GetMapping("/of/parent")
    public ResponseEntity<List<CategoryDTO>> queryCategoryByParentId(@RequestParam("pid") Long parentId){
        //SELECT * FROM tb_category WHERE (parent_id = ?)
        List<Category> categoryList = categoryService.query().eq("parent_id", parentId).list();
        // 转换DTO集合
        List<CategoryDTO> categoryDTOList = CategoryDTO.convertEntityList(categoryList);
        // 返回200
        return ResponseEntity.ok(categoryDTOList);
    }

    //根据品牌id，查询商品分类的集合
    @GetMapping("/of/brand")
    public ResponseEntity<List<CategoryDTO>> queryCategoryByBrandId(@RequestParam("id") Long brandId){
        List<CategoryDTO> categoryDTOList = categoryService.queryCategoryByBrandId(brandId);
        return ResponseEntity.ok(categoryDTOList);
    }
}
